import QtQuick 1.1
import com.nokia.meego 1.0

import "OAuth.js" as OAuthLogic

XmlListModel {
    id: oauthXmlListModel

    property bool oauthEnabled: true
    property string oauthSource
    property string token
    property string secret
    property variant parameters
    property bool oauthLoading: false

    property bool completed: false

    signal oauthFailed
    signal requestError

    function getCredentials() {
        var credentials = new Object();
        credentials["token"] = oauthXmlListModel.token;
        credentials["secret"] = oauthXmlListModel.secret;
        return credentials;
    }

    function getParameters() {
        var parameters = new Array();
        parameters = oauthXmlListModel.parameters
        return parameters;
    }

    function loadXml() {
        oauthLoading = true;
        var credentials = getCredentials();
        var parameters = getParameters();

        var xhr = OAuthLogic.createOAuthHeader("GET", oauthSource, [ ], oauthEnabled ? credentials : undefined, parameters);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Accept-Language", "en");
        xhr.onreadystatechange = function() {
                    if (xhr.readyState === XMLHttpRequest.DONE) {
                        if(xhr.status === 200) {
                            oauthXmlListModel.xml = xhr.responseText;
                            console.log("OAuth successfull on " + oauthSource);
                         }
                        else if(xhr.status === 401) {
                            oauthXmlListModel.oauthFailed();
                            console.log("OAuth failed on " + oauthSource + ": " + xhr.getResponseHeader("www-authenticate"))
                        }
                        else {
                            console.log("Unexpected OAuth status: " + xhr.status)
                        }
                        oauthLoading = false;
                    }
                }
        xhr.onerror = function() {
                    oauthXmlListModel.requestError();
                }
        xhr.send();
    }

    function reload() {
       loadXml();
    }

    onOauthEnabledChanged: if(completed) reload();
    onParametersChanged: if(completed) reload();
    onOauthSourceChanged: if(completed) reload();
    Component.onCompleted: { reload(); completed = true; }
}

